<template>
  <el-row align="middle">
    <el-col :span="8">
      <company-selector width="w-100" v-model="selectCompanyId"/>
    </el-col>
    <el-col :span="2">
      <span>{{ personals?.length }} 人</span>
    </el-col>
    <el-col :offset="12" :span="2">
      <el-button v-if="checkPermission(Permissions.personnel, Action.add)" type="primary"
                 @click="showAddPersonDialog=true">添加员工
      </el-button>
    </el-col>
  </el-row>
  <el-divider/>
  <el-table :data="personals" stripe border>
    <el-table-column label="名字" prop="company_personnel_name"/>
    <el-table-column label="电话" prop="company_personnel_phone"/>
    <el-table-column label="身份证号" prop="company_personnel_sfz"/>
    <el-table-column label="入职时间" prop="time"/>
    <el-table-column label="合同到期时间" prop="dq_time">
      <template #default="{row}">
        <span :class="{'text-red':checkDateExpire(row.dq_time)}">{{ row.dq_time }}</span>
      </template>
    </el-table-column>
    <el-table-column label="身份证正面照片">
      <template #default="{row}">
        <photo-provider v-if="row.company_personnel_sfz_img_z != null"
                        :downloadMethod="item => downloadImage(item, row.company_personnel_sfz_img_z)">
          <photo-consumer :src="getImageUrl(row.company_personnel_sfz_img_z)"
                          :downloadName="row.company_personnel_name + '-身份证正面照'"
                          :key="row.company_personnel_id">
            <el-image class="size-20" :src="getImageUrl(row.company_personnel_sfz_img_z)"/>
          </photo-consumer>
        </photo-provider>
      </template>
    </el-table-column>
    <el-table-column label="身份证反面照片">
      <template #default="{row}">
        <photo-provider v-if="row.company_personnel_sfz_img_f != null"
                        :downloadMethod="item => downloadImage(item, row.company_personnel_sfz_img_f)">
          <photo-consumer :src="getImageUrl(row.company_personnel_sfz_img_f)"
                          :downloadName="row.company_personnel_name + '-身份证反面照'"
                          :key="row.company_personnel_id">
            <el-image class="size-20" :src="getImageUrl(row.company_personnel_sfz_img_f)"/>
          </photo-consumer>
        </photo-provider>
      </template>
    </el-table-column>
    <el-table-column label="毕业证图片">
      <template #default="{row}">
        <photo-provider v-if="row.company_personnel_byz != null"
                        :downloadMethod="item => downloadImage(item, row.company_personnel_byz)">
          <photo-consumer :src="getImageUrl(row.company_personnel_byz)"
                          :downloadName="row.company_personnel_name + '-毕业证'"
                          :key="row.company_personnel_id">
            <el-image class="size-20" :src="getImageUrl(row.company_personnel_byz)"/>
          </photo-consumer>
        </photo-provider>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="{row}">
        <el-popconfirm
            v-if="checkPermission(Permissions.personnel, Action.delete)"
            :title="'确认删除'+row.company_personnel_name + '吗？'"
            @confirm="deletePersonnelFn(row.company_personnel_id)">
          <template #reference>
            <el-button type="danger" size="small" :disabled="deleteLoading">删除</el-button>
          </template>
        </el-popconfirm>
        <el-button type="success"
                   size="small"
                   v-if="checkPermission(Permissions.personnel, Action.edit)"
                   @click="updatePersonal(row)">
          编辑
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <add-person-dialog v-model="showAddPersonDialog" @success="refetch"/>
  <update-person-dialog v-model:person="needUpdatePerson" v-model="showUpdatePersonDialog" @success="refetch"/>
</template>

<script setup lang="ts">
import {useMutation, useQuery} from "@pinia/colada";
import {deletePersonnel, getPersonals} from "../../api/personal.ts";
import {type Ref, ref} from "vue";
import AddPersonDialog from "./components/AddPersonDialog.vue";
import {ElMessage} from "element-plus";
import UpdatePersonDialog from "./components/UpdatePersonDialog.vue";
import type {PersonDTO, PersonVO} from "../../types";
import {type ItemType, PhotoConsumer, PhotoProvider} from "vue3-photo-preview";
import {checkDateExpire, getImageUrl} from "../../utils/utils.ts";
import {saveAs} from "file-saver";
import {downloadFile} from "../../api/file.ts";
import CompanySelector from "../../components/CompanySelector.vue";
import {useUserStore} from "../../store/userStore.ts";
import {Action, Permissions} from "../../types/permissions.ts";
import {useCloned} from "@vueuse/core";

const selectCompanyId = ref<number>()
const showAddPersonDialog = ref(false)
const showUpdatePersonDialog = ref(false)
const needUpdatePerson = ref<PersonVO>({})

let {checkPermission} = useUserStore();

let {data: personals, refetch} = useQuery({
  key: () => ["personals", selectCompanyId.value ?? null],
  query: () => getPersonals(Number(selectCompanyId.value)),
  enabled: () => selectCompanyId.value !== undefined
})

let {mutate: deletePersonnelFn, isLoading: deleteLoading} = useMutation({
  mutation: (id: number) => deletePersonnel(id),
  onSuccess: () => {
    refetch()
    ElMessage.success("删除成功")
  },
  onError: () => {
    ElMessage.error("删除失败")
  }
});

const updatePersonal = (person: Ref<PersonDTO>) => {
  let {cloned} = useCloned(person);
  needUpdatePerson.value = cloned.value;
  showUpdatePersonDialog.value = true;
}

const downloadImage = (item: ItemType, path: string) => {
  downloadFile(path).then(res => {
    saveAs(res.data, item.downloadName + '.' + item.src.split('.').at(-1))
  })
}
</script>

<style scoped>

</style>